package com.zjc.utils.date;

import java.sql.Timestamp;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 日期工具类
 *
 * @author zjc
 * @date 2022-07-1 09:47
 */
public class DateUtils {

    // 以T分隔日期和时间，并带时区信息，符合ISO8601规范
    public static final String PATTERN_ISO = "yyyy-MM-dd'T'HH:mm:ss.SSSZZ";
    public static final String PATTERN_ISO_ON_SECOND = "yyyy-MM-dd'T'HH:mm:ssZZ";
    public static final String PATTERN_ISO_ON_DATE = "yyyy-MM-dd";

    // 以空格分隔日期和时间，不带时区信息
    public static final String PATTERN_DEFAULT = "yyyy-MM-dd HH:mm:ss.SSS";
    public static final String PATTERN_DEFAULT_ON_SECOND = "yyyy-MM-dd HH:mm:ss";


    public static Timestamp getCurrentTime() {
        Date date1 = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat(PATTERN_DEFAULT_ON_SECOND);
        String str = sdf.format(date1);
        Timestamp timestamp = Timestamp.valueOf(str);
        return timestamp;
    }

    public static String getCurrentTimeStr() {
        return new SimpleDateFormat(PATTERN_DEFAULT_ON_SECOND).format(new Date());
    }

    public static String getCurrentTimeStr(String pattern) {
        return new SimpleDateFormat(pattern).format(new Date());
    }

    public static String dateCoverterToStr(Date date){
        return new SimpleDateFormat(PATTERN_DEFAULT_ON_SECOND).format(date);
    }

    public static Date strCoverterToDate(String str){
        SimpleDateFormat formatter = new SimpleDateFormat(PATTERN_DEFAULT_ON_SECOND);
        ParsePosition pos = new ParsePosition(0);
        Date strtodate = formatter.parse(str, pos);
        return strtodate;
    }

    public static String beforeDay(Date now, Integer days) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        calendar.add(Calendar.DAY_OF_MONTH, days);
        Date dBefore = calendar.getTime();
        return new SimpleDateFormat(PATTERN_DEFAULT_ON_SECOND).format(dBefore);
    }
}
